package com.p2p.front.web.controller;

import java.util.Arrays;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.p2p.base.exception.BizException;
import com.p2p.base.model.BaseUser;
import com.p2p.base.page.PageVo;
import com.p2p.base.util.MD5Util;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.dal.model.Transfer;
import com.p2p.front.enums.CanTransferStatus;
import com.p2p.front.enums.TenderReturnStatus;
import com.p2p.front.result.TransferResult;
import com.p2p.front.service.CommonService;
import com.p2p.front.service.LoanInfoService;
import com.p2p.front.service.TenderReturnService;
import com.p2p.front.service.TenderService;
import com.p2p.front.service.TransferService;
import com.p2p.front.service.UserService;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.result.AccountQueryResult;

/**
 * @author ruiqi
 *
 */
@RequestMapping("/transfer")
@Controller
public class TransferController extends BaseController {

	private static final String REDIRECT_TRANSFER_PUBLISHLIST = "redirect:/transfer/publishlist.html";

	private Logger logger = Logger.getLogger(this.getClass());

	@Resource
	private TransferService transferService;

	@Resource
	private TenderService tenderService;

	@Resource
	private TenderReturnService tenderReturnService;

	@Resource
	private LoanInfoService loanInfoService;

	@Resource
	private AccountQueryFacade accountQueryFacade;

	@Resource
	private UserService userService;

	@Resource
	private CommonService commonService;
	
	// 可以转让的投资
	@RequestMapping("/canpublishlist")
	public String canpublishlist(PageVo form, Model model) {
		Long start=System.currentTimeMillis();
		BaseUser user = getCurrentUser();
		String uid = user.getId();
		form.getParams().put("uid", uid);
		form.getParams().put("status", TenderReturnStatus.RECYCLING.getCode()+"");
		// 改为TenderReturn
		PageVo page = tenderReturnService.canPublishListPage(user.getLongId(),form);
		model.addAttribute("page", page);
		Long end= System.currentTimeMillis();
		System.out.println(end-start);
		return "transfer/canpublishlist";
	}

	@RequestMapping("/publishlist")
	public String publishList(PageVo form, ModelMap map) {
		BaseUser user = getCurrentUser();
		form.getParams().put("uid", user.getId());
		PageVo page = transferService.listPage(form);
		map.addAttribute("page", page);
		return "/transfer/publishlist";
	}

	@RequestMapping("/publishdetail")
	public String publishDetail(@RequestParam Long tid, Model model) {
		BaseUser user = getCurrentUser();
	/*	boolean canTransfer=transferService.canTransferVeryStrict(user.getLongId(), tid);
		if(!canTransfer){
			throw new BizException("TRANSFER_ERROR", "不能转让，不满足债权转让的前提条件");
		}*/
		// 发布之前，需要“预先”计算各种指标，与最终执行发布的方法的逻辑是一样的
		Long uid = super.getCurrentUser().getLongId();
		Transfer transfer = transferService.prevCreateTransfer2(uid, tid);
		if (transfer != null) {
			LoanInfo loan = loanInfoService.getLoanInfoById(transfer.getLid());
			model.addAttribute("transfer", transfer);
			model.addAttribute("loan", loan);
		} else {
			logger.error("transfer is null when publish-detail");
			throw new BizException("transfer_error", "债权转让创建失败");
		}
		return "/transfer/publishdetail";
	}

	@RequestMapping("/publish")
	public String publish(@RequestParam Long tid,@RequestParam String paypwd,
			@RequestParam String transpwd, Model map) {
		BaseUser user = getCurrentUser();
		CanTransferStatus canTransfer=transferService.canTransferVeryStrict(user.getLongId(), tid);
		if(canTransfer!=CanTransferStatus.OK){
			throw new BizException("TRANSFER_ERROR", "不能转让，不满足债权转让的前提条件,"+canTransfer.getMemo());
		}
		String realPaypwd = userService.findById(user.getId()).getPaypwd();
		boolean bothBlank = StringUtils.isBlank(realPaypwd)
				&& StringUtils.isBlank(paypwd);
		if (bothBlank || MD5Util.sha1(paypwd).equals(realPaypwd)) {
			TransferResult result = transferService.createTransfer2(
					Long.valueOf(user.getId()), tid, transpwd);
			if (!result.isSuccess()) {
				map.addAttribute("result", result.getResultCode());
			}
		} else {
			throw new BizException("TRANSFER_ERROR", "不能转让，支付密码不正确");
		}
		return REDIRECT_TRANSFER_PUBLISHLIST;
	}

	// 承接
	@RequestMapping("/acceptdetail")
	public String acceptdetail(Long transferid, Model model) {
		BaseUser user = getCurrentUser();
		Map<String, Object> transfer = transferService
				.getTransferDetail(transferid);
		AccountQueryResult result = accountQueryFacade.getAccountInfo(user
				.getAccountNo());
		if (result.isSuccess()) {
			model.addAttribute("account", result.getAccountVO());
		} else {
			throw new BizException("ACCOUNT_ERROR", "账户信息查询失败");
		}
		model.addAttribute("transfer", transfer);
		return "/transfer/acceptdetail";
	}

	@RequestMapping("/accept")
	public String accept(@RequestParam Long transferid, String paypwd, String transpwd,
			ModelMap map) {
		BaseUser user = getCurrentUser();
		boolean canAccept=transferService.canAccept(transferid,user.getLongId(),paypwd,transpwd);
		if(!canAccept){
			throw new BizException("TRANSFER_ERROR", "不满足承接债权的条件");
		}
		TransferResult result = transferService.acceptTransfer(transferid,
				Long.valueOf(user.getId()), transpwd);

		if (!result.isSuccess()) {
			map.addAttribute("result", result.getResultCode());
		}
		return "redirect:/transfer/acceptlist.html";
	}

	@RequestMapping("/acceptlist")
	public String acceptlist(PageVo form, ModelMap map) {
		BaseUser user = getCurrentUser();
		form.getParams().put("ruid", user.getId());
		PageVo page = transferService.listPage(form);
		map.addAttribute("page", page);
		return "/transfer/acceptlist";
	}

	// 跳转页面
	@RequestMapping("/index")
	public String index() {
		return "transfer/index";
	}

	@RequestMapping("/about")
	public String about() {
		return "transfer/index";
	}

	@RequestMapping("/cancel")
	public String cancel(@RequestParam Long id) {
		BaseUser user = getCurrentUser();
		transferService.cancel(id, user.getLongId());
		return REDIRECT_TRANSFER_PUBLISHLIST;
	}

	@RequestMapping("/cancelbylid")
	public void cancelByLid(@RequestParam Long lid, HttpServletResponse response) {
		BaseUser user = getCurrentUser();
		transferService.cancelTransferByLid(lid);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("ok", 1);
		super.returnJsonObject(response, jsonObject);
	}
	@RequestMapping("/cancelbytid")
	public void cancelByTid(@RequestParam Long tid, HttpServletResponse response) {
		transferService.cancelTransferByTid(Arrays.asList(tid));
	}
	
	@Deprecated
	// transferService.acceptTransfer已经做了检查
	// 检查承接的债权转让，是不是自己的
	private void checkIsAcceptMyself(BaseUser user, Long transferid) {
		Map<String, Object> transfer = transferService
				.getTransferDetail(transferid);
		Integer uid = MapUtils.getInteger(transfer, "uid");
		Integer loginUid = user.getIntId();
		if (uid.equals(loginUid)) {
			throw new BizException("不能承接自己发布的债权");
		}

	}
}
